import { Avatar, Icon, Menu, Spin } from 'antd';
import { FormattedMessage } from 'umi-plugin-react/locale';
import React from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import { authSite } from '../../../config/defaultSettings';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';

class AvatarDropdown extends React.Component {
  onMenuClick = event => {
    const { key } = event;
    if (key === 'logout') {
      const { dispatch } = this.props;
      if (dispatch) {
        dispatch({
          type: 'login/logout'
        });
      }
    } else {
      const { origin, pathname } = window.location;
      const homeUrl = authSite && authSite.homeUrl ? authSite.homeUrl : `${origin}/#`;
      const homeURL = new URL(homeUrl);
      if (homeURL.origin + homeURL.pathname === origin + pathname) {
        router.push(`/center/account/${key}`);
      } else {
        window.open(`${homeUrl}/center/account/${key}`, 'authorization');
      }
    }
  };

  render() {
    const { currentUser, menu } = this.props;
    const menuHeaderDropdown = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={this.onMenuClick}>
        {menu && (
          <Menu.Item key="basic">
            <Icon type="user" />
            <FormattedMessage id="menu.account.basic" defaultMessage="account center" />
          </Menu.Item>
        )}
        {menu && (
          <Menu.Item key="security">
            <Icon type="setting" />
            <FormattedMessage id="menu.account.settings" defaultMessage="account settings" />
          </Menu.Item>
        )}
        {menu && <Menu.Divider />}
        <Menu.Item key="logout">
          <Icon type="logout" />
          <FormattedMessage id="menu.account.logout" defaultMessage="logout" />
        </Menu.Item>
      </Menu>
    );
    return currentUser ? (
      <HeaderDropdown overlay={menuHeaderDropdown}>
        <span className={`${styles.action} ${styles.account}`}>
          <Avatar size="small" className={styles.avatar} src={currentUser.headSculpture} alt="avatar" onError={() => true} />
          <span className={styles.name}>{currentUser.nikeName || currentUser.username}</span>
        </span>
      </HeaderDropdown>
    ) : (
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8
        }}
      />
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser
}))(AvatarDropdown);
